package com.platform.server.controller;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.http.client.methods.HttpPost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.paltform.server.entity.SysUser;
import com.platform.server.dao.DiscountDao;
import com.platform.server.service.ComplaintService;
import com.platform.server.service.DiscountService;
import com.platform.server.service.MessageService;
import com.platform.server.service.OrderService;
import com.platform.server.util.HttpUtil;
import com.platform.server.util.StringTools;

@Controller
public class ComplaintController {

	
	@Autowired
	private ComplaintService complaintService;
	@Autowired
	private MessageService messageService;
	/**
	 * 查看投诉管理
	 * @return
	 */
	@RequestMapping("/selectComplaintList")
	public Object selectComplaintList(HttpServletRequest request,String id,String startTime,String endTime,String is_acceptance,String username,String mobile,String order_id,String acceptance){
		if(!StringTools.isEmpty(id)){
			Map<String, Object> selectComplaintInfo = complaintService.selectComplaintInfo(id);
			List<Map<String,Object>> selectComplaintPic = complaintService.selectComplaintPic(selectComplaintInfo.get("id").toString());
			if(selectComplaintInfo.get("appea_id")!=null){
				List<Map<String,Object>> selectComplaintPic2 = complaintService.selectComplaintPic(selectComplaintInfo.get("appea_id").toString());
				request.setAttribute("list2", selectComplaintPic2);
			}
			request.setAttribute("map", selectComplaintInfo);
			request.setAttribute("list", selectComplaintPic);
			request.setAttribute("acceptance", acceptance);
			return "/ui/complaint/complaint_info.jsp";
		}
		List<Map<String,Object>> lists = complaintService.selectComplaintList( startTime, endTime, is_acceptance, username, mobile, order_id);
		for (Map<String, Object> map : lists) {
			String selectIsComplaint = complaintService.selectIsComplaint(map.get("order_id").toString());
			if(StringTools.isEmpty(selectIsComplaint)||selectIsComplaint.equals("0")){
				map.put("is_acceptance", 0);
			}else{
				map.put("is_acceptance", selectIsComplaint);
			}
		}
		request.setAttribute("lists", lists);
		request.setAttribute("nums", lists.size());
		return "/ui/complaint/complaint_list.jsp";
	}
	/***
	 * 受理 
	 * @param acceptance_content
	 * @param id
	 * @param response
	 * @param session
	 * @throws Exception
	 */
	@RequestMapping("/updateComplaint")
	public void updateComplaint(String acceptance_content,String id,String orderId,String type,HttpServletResponse response,
			HttpSession session) throws Exception{
		Map<String,Object> map = new HashMap<>();
		map.put("id", id);
		map.put("acceptance_content", acceptance_content);
		map.put("is_acceptance","1");
        Map<String, Object> selectComplaintInfo = complaintService.selectComplaintInfos(id);
        if(selectComplaintInfo.get("is_acceptance")!=null&&selectComplaintInfo.get("is_acceptance").equals("0")){
			SysUser attribute = (SysUser) session.getAttribute("user");
			if(attribute==null){
				response.sendRedirect("http://hanya.htx328.com/htx-backer/index.jsp");
			}else{
				map.put("acceptance_username", attribute.getSys_name());
				int  flag = complaintService.updateComplaint(map);
			            //查看订单详情
				        Map<String, Object> selectOrderInfo = complaintService.selectOrderInfo(orderId);
				        String server_user_id = selectOrderInfo.get("server_user_id").toString();
				        Double sum_price = Double.parseDouble(selectOrderInfo.get("sum_price").toString());
				        Double money = 0D;
				        Double dismoney = 0D;
				        //查看平台手续费
				        DecimalFormat df = new DecimalFormat("######0.00");
				        Double discount =  complaintService.selectPlatformDiscount();
				        if (discount > 0) {
				            money = Double.parseDouble(df.format(sum_price * (discount / 100)));
				        	dismoney=money;
				        }
				        //查看vip服务费折扣
				        String selectisVip = complaintService.selectisVip(selectOrderInfo.get("server_user_id").toString());
				        if(!StringTools.isEmpty(selectisVip)&&selectisVip.equals("1")){
				        	String selectis_vip = complaintService.selectis_vip(selectOrderInfo.get("server_user_id").toString(), "2");
				        	if(!StringTools.isEmpty(selectis_vip)&&selectis_vip.equals("1")){
				            	Double selectVipDiscont = complaintService.selectVipDiscont();
					        	money = Double.parseDouble(df.format(money * (selectVipDiscont / 100)));
				        	}
				        }
				        //查看企业会员服务费折扣
				        int selectUserAuthentication = complaintService.selectUserAuthentication(selectOrderInfo.get("server_user_id").toString());
				        if(selectUserAuthentication==1){
				     	   if(dismoney!=money){
				     		   money=dismoney;
				     	   }
				     	   Double selectEntUserDiscont = complaintService.selectEntUserDiscont();
				 		 	money = Double.parseDouble(df.format(money * (selectEntUserDiscont / 100)));
				        }
				        
				        Double _money = sum_price - money;
				        // 平台余额
				        Map<String, Object> map3 = complaintService.selectUserMoney("1");
				        String platform_money = map3.get("money")
				                                    .toString();

				        // 服务者的余额
				        Map<String, Object> map1 = complaintService.selectUserMoney(server_user_id);
				        String money1 = map1.get("money")
				                            .toString();
				        String map4 = complaintService.selectUserMoney2(selectOrderInfo.get("user_id").toString());
				        String money2 = map4;
				        Double royaltytotal = 0D;
				        //投诉成功
				        if(type.equals("0")){
				        	Map<String, Object> map2 = new HashMap<>();
					        map2.put("status", "已完成");
					        map2.put("orderid", orderId);
					        complaintService.confirmOrder(map2);
				        	 if (selectOrderInfo.get("discountid")!=null) {
						            //修改优惠券状态
				        		  complaintService.updateDiscountStatus(Integer.parseInt(selectOrderInfo.get("discountid").toString()));
						        }
				        		String selectUserIntegral = complaintService.selectUserIntegral(selectOrderInfo.get("user_id").toString());
				        		if(!selectOrderInfo.get("reality_price").toString().equals("0.00")){
									selectUserIntegral=String.valueOf(Integer.parseInt(selectUserIntegral)-Integer.parseInt(selectOrderInfo.get("reality_price").toString().substring(0,selectOrderInfo.get("reality_price").toString().indexOf("."))));
									complaintService.returnUserIntegral(selectOrderInfo.get("user_id").toString(),selectUserIntegral);
									complaintService.insertIntegralRecord(selectOrderInfo.get("user_id").toString(),selectOrderInfo.get("reality_price").toString().substring(0,selectOrderInfo.get("reality_price").toString().indexOf(".")), "积分扣减", null);
						            }
						        if (selectOrderInfo.get("integral")!=null) {
						            //退还用户积分
						        	complaintService.returnUserIntegral(selectOrderInfo.get("user_id").toString(),String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(selectOrderInfo.get("integral").toString())));
						            //最后添加该用户的积分记录
						        	complaintService.insertIntegralRecord(selectOrderInfo.get("user_id").toString(), String.valueOf(Integer.parseInt(selectUserIntegral)+Integer.parseInt(selectOrderInfo.get("integral").toString())), "积分返还", null);
						        }
				        	//complaintService.insertCancelOrder(server_user_id, "30", "服务违约支出", orderId, Double.valueOf(money) - Double.valueOf(30) + "", "2", platform_money, null);
				        	//complaintService.insertCancelOrder(selectOrderInfo.get("user_id").toString(), "30", "服务方违约金收入",orderId, money2 +30+ "", "1", platform_money, null);
				        	//_money=_money-30;
				        	_money=Double.parseDouble(selectOrderInfo.get("reality_price").toString());
				        	complaintService.insertCancelOrder(selectOrderInfo.get("user_id").toString(), _money + "", "完成", orderId, Double.valueOf(money2) + _money + "","1", Double.valueOf(platform_money) - _money + "", 0 + "");
				              //加入服务者余额
				              Map<String, Object> hashMap = new HashMap<String, Object>();
				              hashMap.put("user_id", selectOrderInfo.get("user_id").toString());
				              hashMap.put("money", selectOrderInfo.get("reality_price").toString());
				              complaintService.updateServerUserMoney(hashMap);
				              complaintService.returnUserMoney("1", Double.valueOf(platform_money) - _money-royaltytotal + "");
				              List<Map<String,Object>> selectComplaint = complaintService.selectComplaint(orderId);
				              for (Map<String, Object> map5 : selectComplaint) {
							if(map5.get("is_status")!=null&&map5.get("is_status").toString().equals("0")){
					              messageService.insertSystemMessage(selectComplaintInfo.get("user_id").toString(), "你的投诉已通过",  "你的投诉已通过");	
							}	
							if(map5.get("is_status")!=null&&map5.get("is_status").toString().equals("1")){
					              messageService.insertSystemMessage(selectComplaintInfo.get("asappeal_id").toString(), "您的申诉被驳回",  "您的申诉被驳回");	
							}	
							}
				        }else{
				        	//String resXml = HttpUtil.postData("http://hanya.htx328.com/hua-tianxia/server/demandSure","demandid="+selectOrderInfo.get("server_id").toString()+"&orderid="+selectOrderInfo.get("id").toString());
				       	 Map<String, String> params=new HashMap<String, String>();
						 params.put("demandid",selectOrderInfo.get("server_id").toString());
						 params.put("orderid",selectOrderInfo.get("id").toString());
						 String resXml = HttpUtil.post("http://hanya.htx328.com/hua-tianxia/server/demandSure",params);
				        	/*
//				        	   royaltytotal += royalty(selectOrderInfo.get("server_user_id").toString(), selectOrderInfo, platform_money, money1,_money);
				        	royaltytotal += royalty(selectOrderInfo.get("server_user_id").toString(), selectOrderInfo, platform_money, money1,Double.parseDouble(selectOrderInfo.get("reality_price").toString()));
						        royaltytotal += royalty(selectOrderInfo.get("user_id").toString(), selectOrderInfo, platform_money, money2,Double.parseDouble(selectOrderInfo.get("reality_price").toString()));
						        
				        	complaintService.insertCancelOrder(server_user_id, _money + "", "完成", orderId, Double.valueOf(money1) + _money + "","1", Double.valueOf(platform_money) - _money + "", sum_price - _money + "");
				             
				        	   //查看积分使用方式
				            Map<String, Object> hashMap1 = complaintService.selectIntegeralWay();
				            //查看用户积分
				            Map<String, Object> hm = complaintService.selectMyIntegral(selectOrderInfo.get("server_user_id").toString());
				            Integer integral = Integer.parseInt(hm.get("integral")
				                                                  .toString()) + Integer.parseInt(hashMap1.get("server")
				                                                                                         .toString());
				            //服务完成后给该用户增加积分
				            int flag2 = complaintService.updateIntegral(selectOrderInfo.get("server_user_id").toString(), integral.toString());
				            //最后添加该用户的积分记录
				            int flag3 = complaintService.insertIntegralRecord(selectOrderInfo.get("server_user_id").toString(), hashMap1.get("server")
				                                                                                         .toString(), "服务完成", null);
				        	//加入服务者余额
				              Map<String, Object> hashMap = new HashMap<String, Object>();
				              hashMap.put("user_id", server_user_id);
				              hashMap.put("money", _money);
				              complaintService.updateServerUserMoney(hashMap);
				              complaintService.returnUserMoney("1", Double.valueOf(platform_money) - _money-royaltytotal + "");
				              */
						 List<Map<String,Object>> selectComplaint = complaintService.selectComplaint(orderId);
			              for (Map<String, Object> map5 : selectComplaint) {
						if(map5.get("is_status")!=null&&map5.get("is_status").toString().equals("0")){
				              messageService.insertSystemMessage(selectComplaintInfo.get("asappeal_id").toString(), "您的投诉被驳回",  "您的投诉被驳回");	
						}	
						if(map5.get("is_status")!=null&&map5.get("is_status").toString().equals("1")){
				              messageService.insertSystemMessage(selectComplaintInfo.get("user_id").toString(), "你的申诉已通过",  "你的申诉已通过");	
						}	
						}
				        }
			    
				
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("flag", flag);
		        response.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
			}
        }
	}
	  //提成
    public Double royalty(String user_id,Map order,String platform_money,String money1,Double money2){
    	  Double royaltytotal = 0D;
    	 DecimalFormat df = new DecimalFormat("######0.00");
    	 //查询上一级用户
        String selectParent = complaintService.selectParent(user_id);
		Map<String, Object> selectRate2 = complaintService.selectRate();
		  Double royalty = 0D;
		
        if(!StringTools.isEmpty(selectParent)){
   	    	  //查看顶级是否企业
      	       int selectUserAuthentication2 = complaintService.selectUserAuthentication(selectParent);
   	    	  //查询顶级是否vip
   	    	  String selectEntMember = complaintService.selectisVip(selectParent);
   	    	  //加入提成
   	    	  if(!StringTools.isEmpty(selectEntMember)&&selectEntMember.equals("1")){
   	    		  	if(selectUserAuthentication2==1){
   	    		  	 Double selectRate = Double.parseDouble( selectRate2.get("vip_ent_level").toString());
     	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
     	    		 complaintService.insertRoyaltyOrder(selectParent, royalty + "", "提成", order.get("order_id").toString(), Double.valueOf(money1) + royalty + "", "1", Double.valueOf(platform_money) -royalty+"" , null,user_id);
     	    		  //加入提成
   	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
   	    	        hashMap.put("user_id", selectParent);
   	    	        hashMap.put("money", royalty);
   	    	     complaintService.updateServerUserMoney(hashMap);
   	    		  	}else{
   	    		  	 Double selectRate = Double.parseDouble( selectRate2.get("vip_one_level").toString());
        	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
        	    		  complaintService.insertRoyaltyOrder(selectParent, royalty + "", "提成", order.get("order_id").toString(), Double.valueOf(money1) + royalty + "","1", Double.valueOf(platform_money) -royalty+"" , null,user_id);
        	    		  //加入提成
       	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
       	    	        hashMap.put("user_id", selectParent);
       	    	        hashMap.put("money", royalty);
       	    	     complaintService.updateServerUserMoney(hashMap);
   	    		  	}
   	    	  }else{
   	    		 	if(selectUserAuthentication2==1){
   	    		 		 Double selectRate = Double.parseDouble( selectRate2.get("ordinary_ent_level").toString());
   	    	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
   	    	    		complaintService.insertRoyaltyOrder(selectParent, royalty + "", "提成",  order.get("order_id").toString(), Double.valueOf(money1) + royalty + "", "1", Double.valueOf(platform_money) -royalty+"" , null,user_id);
   	    	    		 //加入提成
   	    	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
   	    	    	        hashMap.put("user_id", selectParent);
   	    	    	        hashMap.put("money", royalty);
   	    	    	     complaintService.updateServerUserMoney(hashMap);
   	    		 	}else{
     	    			 Double selectRate = Double.parseDouble( selectRate2.get("ordinary_one_level").toString());
      	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
      	    		complaintService.insertRoyaltyOrder(selectParent, royalty + "", "提成",  order.get("order_id").toString(), Double.valueOf(money1) + royalty + "","1", Double.valueOf(platform_money)-royalty +"" , null,user_id);
      	    		 //加入提成
       	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
       	    	        hashMap.put("user_id", selectParent);
       	    	        hashMap.put("money", royalty);
       	    	     complaintService.updateServerUserMoney(hashMap);
   	    		 	}
   	    	  }
        	
   	    	royaltytotal=royalty;
     	   //查询是否二级
     	      String parent = complaintService.selectParent(selectParent);
     	      if(!StringTools.isEmpty(parent)){
     	    	 royalty=0.D;
     	    	  //查询顶级是否vip
     	    	  String selectEntMember2 = complaintService.selectisVip(parent);
     	    	//加入提成
     	    	  if(!StringTools.isEmpty(selectEntMember2)&&selectEntMember2.equals("1")){
     	    	  	 Double selectRate = Double.parseDouble( selectRate2.get("vip_two_level").toString());
     	    		  royalty = Double.parseDouble(df.format(money2 * (selectRate / 100)));
     	    		 complaintService.insertRoyaltyOrder(parent, royalty + "", "提成", order.get("order_id").toString(), Double.valueOf(money1) + royalty + "", "1", Double.valueOf(platform_money) -royalty+"" , null,user_id);
     	    		  //加入服务者余额
     	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
     	    	        hashMap.put("user_id", parent);
     	    	        hashMap.put("money", royalty);
     	    	       complaintService.updateServerUserMoney(hashMap);
     	    	  }else{
     	    		 Double selectRate = Double.parseDouble( selectRate2.get("ordinary_two_level").toString());
    	    		  royalty = Double.parseDouble(df.format(money2* (selectRate / 100)));
    	    		  complaintService.insertRoyaltyOrder(parent, royalty + "", "提成",order.get("order_id").toString(), Double.valueOf(money1) + royalty + "", "1", Double.valueOf(platform_money) -royalty+"" , null,user_id);
    	    		  //加入服务者余额
   	    	        Map<String, Object> hashMap = new HashMap<String, Object>();
   	    	        hashMap.put("user_id", parent);
   	    	        hashMap.put("money", royalty);
   	    	     complaintService.updateServerUserMoney(hashMap);
     	    	  }
     	    	 royaltytotal=+royalty;
     	      }
     	      
        }
    	return royaltytotal;
    }
}
